<!--table中显示头像
https://www.cnblogs.com/congfeicong/p/11038119.html
-->
<template>
  <div>
    <el-row>
      <el-col :span="15">
        <el-button @click="selectAllOrNo">全选/反选</el-button>
        <el-button type="primary" @click="save('query','',true)">查看</el-button>
        <el-button type="primary" @click="save('add','',true)">添加</el-button>
        <el-button type="primary" @click="save('update','material',true)">修改</el-button>
        <el-button type="primary" @click="del('del')">删除</el-button>
      </el-col>
      <el-col :span="5">
        <!-- 搜索框 -->
        <span>
          <el-input placeholder="请输入搜索内容" v-model="search"></el-input>
        </span>
      </el-col>
      <el-col :span="1">
        <!-- 搜索按钮 -->
        <el-button class="ico" icon="el-icon-search" @click="pageQuery"></el-button>
      </el-col>
    </el-row>

    <hr/>
    <div class="block">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[100, 200, 300, 400]"
        :page-size="size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalSize">
      </el-pagination>
    </div>
    <el-table
      ref="multipleTable"
      :data="tableData"
      tooltip-effect="dark"
      style="width: 100%"
      @selection-change="handleSelectionChange">
      <el-table-column
        type="selection"
        width="55">
      </el-table-column>
      <el-table-column label="预览图" prop="preImg" width="120">
        　　
        <template slot-scope="scope">
              <div v-if="scope.row.preImg">
          　　　　<img :src="getImgsURL(scope.row.preImg)" width="80" height="80" class="head_pic"/>
          　　</div>
              <div v-else-if="scope.row.otherPre">
            　　　　<img :src="scope.row.otherPre" width="80" height="80" class="head_pic"/>
            　　</div>
        </template>
      </el-table-column>
      <el-table-column
        prop="userId"
        label="作者"
        width="180"
      >
      </el-table-column>
      <el-table-column
        prop="title"
        label="标题"
        width="180">
      </el-table-column>
      <!--      <el-table-column-->
      <!--        prop="descre"-->
      <!--        label="描述"-->
      <!--        width="180">-->
      <!--      </el-table-column>-->


      <el-table-column
        prop="channelName"
        label="所属频道"
        width="180"
      >


      </el-table-column>


      <el-table-column
        prop="resourceFile"
        label="资源文件"
        width="400"
      >
        <template slot-scope="scope">

          <!-- 图片有多张的情况 先分隔为数组 然后利用v-for 遍历得到 src  -->
          <div v-if="scope.row.resourceFile">
            <div v-for="(item,index) in scope.row.resourceFile.split('&&')" :key="index" class="table-flex">
              <!--            <a :href="baseURL+item" target="_blank">{{getFileName(item)}}</a>-->
              <a :href="fileServer+item" target="_blank">{{getFileName(item)}}</a>
              <!--            <el-image style="width: 50px; height: 50px; margin-right: 10px;" :src="getImgsURL(item)" ></el-image>-->
            </div>
          </div>
          <div v-else-if="scope.row.otherResourceFile">
            <div v-html="scope.row.otherResourceFile"></div>
          </div>

        </template>
      </el-table-column>
      <el-table-column
        prop="resourceLink"
        label="资源链接"
        width="180"
      >
        <template slot-scope="scope">

          <!-- 图片有多张的情况 先分隔为数组 然后利用v-for 遍历得到 src  -->
          <div v-html="stringUtil.replace(scope.row.resourceLink,'\n','<br/>')"></div>

        </template>
      </el-table-column>
      <el-table-column
        prop="crDate"
        label="发布时间"
        width="180"
      >
        <template slot-scope="scope">{{dateUtil.stringParseDate( scope.row.crDate ,dateUtil.NOSS)}}</template>
      </el-table-column>
      <el-table-column
        prop="moDate"
        label="修改时间"
        width="180"
      >
        <template slot-scope="scope">{{dateUtil.stringParseDate( scope.row.moDate ,dateUtil.NOSS)}}</template>
      </el-table-column>

    </el-table>
    <div class="block">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[100, 200, 300, 400]"
        :page-size="size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalSize">
      </el-pagination>
    </div>
  </div>
</template>

<script>
  import {ArticalPageReq} from "../../req/ArticalPageReq";
  import {ContentType} from "../../constant/ContentType";
  import {StringUtil} from "../../../utils/StringUtil";
  import {ResultStatus} from "../../constant/ResultStatus";
  import {DateUtil} from "../../../utils/DateUtil";
  import {Handle} from "../../constant/Handle";
  import {User} from "../req/User";
  import configs from '@/config/'
  /**
   * el-column 展示多张图片
   */
  export default {
    data() {
      return {
        tableData: [],//返回的表格数据
        multipleSelection: [], //选中的表格数据
        selectFlag: true,//全选开关

        currentPage: 1,
        search: "",//搜索字段
        totalSize: 1,
        size: 100,
        dateUtil: DateUtil,
        baseURL: this.$axios.defaults.baseURL,
        baseIMG: this.$axios.defaults.baseIMG,
        stringUtil: StringUtil,
        fileServer: this.$axios.defaults.fileServer,

      }
    },

    methods: {
      toggleSelection(rows) {
        if (rows) {
          rows.forEach(row => {
            this.$refs.multipleTable.toggleRowSelection(row);
          });
        } else {
          this.$refs.multipleTable.clearSelection();
        }
      },
      handleSelectionChange(val) {
        this.multipleSelection = val;
      },
      /**
       * 全选/反选
       */
      selectAllOrNo() {
        if (this.selectFlag) {
          this.toggleSelection(this.tableData);
        } else {
          this.toggleSelection();
        }
        this.selectFlag = !this.selectFlag;
      },
      handleSizeChange(val) {
        this.size = val;
        this.pageQuery();
      },
      handleCurrentChange(val) {
        this.currentPage = val;
        this.pageQuery();
      },
      save(handle, type, adminFlag) {
        let id = "";
        if (handle == Handle.UPDATE || handle == Handle.QUERY) {
          if (this.multipleSelection.length < 1) {
            this.$notify(StringUtil.warning("请选中数据行"))
            return;
          }
          if (this.multipleSelection.length > 1) {
            this.$notify(StringUtil.warning("请不要多选"))
            return;
          }
          id = this.multipleSelection[0].id;
        }
        switch (handle) {
          case Handle.QUERY:
            this.$router.push({path: '/ArticalDetails?id=' + id});
            break;
          case Handle.UPDATE:
            this.$router.push({path: '/articalAdd', query: {id: id, handle: Handle.UPDATE}});
            break;
          case Handle.ADD:
            this.$router.push({path: "/articalAdd"});
            break;
          default:
            break;
        }

      },
      /**
       * 分布搜索
       */
      pageQuery() {
        let articaPageReq = new ArticalPageReq();
        articaPageReq.size = this.size;
        articaPageReq.page = this.currentPage;
        articaPageReq.descre = this.search;
        this.$axios
          .post('/artical/queryPage',
            articaPageReq, //转成json
            ContentType.APPLICATION_JSON,
          )
          .then((response) => {

            let datas = response.data;

            if (datas.code != ResultStatus.SUCCESS) {
              this.$notify(StringUtil.warning(datas.msg));
              return;
            }
            let datas2 = datas.data;
            this.totalSize = datas2.totalSize;
            let list = datas2.list;
            for (let i = 0; i < list.length; i++) {
              //替换失效的文件服务
              let item = list[i];
              let descre =  StringUtil.replace(item.descre,configs.invalidFileserver,configs.replateFileserver)
              let otherPre = StringUtil.replace(item.otherPre,configs.invalidFileserver,configs.replateFileserver)
              let otherResourceFile = StringUtil.replace(item.otherResourceFile,configs.invalidFileserver,configs.replateFileserver)
              item.descre = descre;
              item.otherPre = otherPre;
              item.otherResourceFile = otherResourceFile
              let channelList = item.channelList;
              if (channelList == null) {
                continue;
              }
              let channels = "";
              for (let j = 0; j < channelList.length; j++) {
                if (j != 0) {
                  channels += ",";
                }
                channels += channelList[j].channelName;
              }
              item.channelName = channels
              list[i] = item;

            }
            this.tableData = list;
          })
          .catch((error) => {
            console.log(error);
            let datas = error.data;
            this.$notify(StringUtil.warning(datas.msg));
          })
      },
      /**
       * 预览图
       * @param data
       * @returns {string}
       */
      getImgsURL(data) {
        if (StringUtil.checkNull(data)) {
          return this.baseIMG;
        }
        return this.fileServer + StringUtil.replace(data, '\\', '/');
      },
      /**
       * 删除
       * @param handler
       */
      del: async function (handler) {
        if (this.multipleSelection.length < 1) {
          this.$notify(StringUtil.warning("请选中数据行"))
          return;
        }
        let flag = await this.confirmBox();
        if (!flag) {
          return;
        }

        for (let i = 0; i < this.multipleSelection.length; i++) {
          let user = new User();
          user.id = this.multipleSelection[i].id;
          user.handle = Handle.DEL;
          this.$axios
            .post('/artical/save',
              user, //转成json
              ContentType.APPLICATION_JSON,
            )
            .then((response) => {

              let datas = response.data;
              if (datas.code == ResultStatus.SUCCESS) {
                this.$notify(StringUtil.success(datas.msg));
              } else {
                this.$notify(StringUtil.warning(datas.msg));

              }
            })
            .catch((error) => {
              console.log(error);
              let datas = error.data;
              this.$notify(StringUtil.warning(datas.msg));
            })
        }
        //location.reload();//重新加载当前页面
        this.pageQuery();
      },
      /**
       * 确认框
       * @returns {boolean}
       */
      confirmBox: async function () {
        let flag = false;
        await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$message({
            type: 'success',
            message: '删除中。。。!'
          });
          flag = true;
        }).catch(() => {
          this.$message({
            type: 'warning',
            message: '已取消删除'
          });
          flag = false;
        });
        return flag;
      },
      /**
       * 获取文件名
       * @param file
       */
      getFileName: function (file) {
        if (StringUtil.checkNull(file)) {
          return "";
        }
        let split = file.split('/');
        return split[split.length - 1];
      },


    },
    mounted() {
      this.pageQuery();
    }
  }
</script>

<style scoped>
  a {
    text-decoration: underline;
  }
</style>
